<template>
    <div style="border:1px solid red;">
        <f-popover ref="popover" position="bottom" :pop-class-name="c('popWrapper')">
            <input type="text" :value="formattedvalue" @input="onInput" @change="onChange" ref="input"/>
            <template slot="content">
                <div class="f-date-picker-pop" @selectstart.prevent>
                    <div class="f-date-picker-nav">
                        <span :class="c('prevYear','navItem')" @click="onClickPrevYear"><f-icon name="leftleft"></f-icon></span>
                        <span :class="c('prevMonth','navItem')" @click="onClickPrevMonth"><f-icon name="left"></f-icon></span>
                        <span :class="c('yearAndMonth')" @click="onClickMonth">
                            <span>{{display.year}}年</span>
                            <span>{{display.month+1}}月</span>
                        </span>
                        <span :class="c('nextMonth','navItem')" @click="onClickNextMonth"><f-icon name="right"></f-icon></span>
                        <span :class="c('nextYear','navItem')" @click="onClickNextYear"><f-icon name="rightright"></f-icon></span>
                    </div>
                    <div class="f-date-picker-panels">
                        <div class="f-date-picker-content">
                            <template v-if="mode==='month'">
                                <div :class="c('selectMonth')">
                                    <div>
                                        <select name="year" @change="onSelectYear" :value="display.year">
                                            <option v-for="year in years" :value="year" :key="year">{{year}}</option>
                                        </select>年
                                        <select name="month" @change="onSelectMonth" :value="display.month">
                                            <option v-for="month in helper.range(0,12)" :value="month" :key="month">{{month+1}}</option>
                                        </select>月
                                    </div>
                                    <div>
                                        <button @click="mode='day'">返回</button>
                                    </div>
                                </div>
                            </template>
                            <template v-else>
                                <div class="f-date-picker-content">
                                    <div :class="c('weekdays')">
                                <span :class="c('weekday')" v-for="i in [1,2,3,4,5,6,0]" :key="i">
                                    {{weekdays[i]}}
                                </span>
                                    </div>
                                    <div :class="c('row')" v-for="i in helper.range(1,6+1)" :key="i">
                                <span :class="[c('cell')
                                ,{currentMonth:isCurrentMonth(getVisibleDay(i,j))
                                ,selected:isSelected(getVisibleDay(i,j))
                                ,today:isToday(getVisibleDay(i,j))
                                }]"
                                      v-for="j in helper.range(1,7+1)"
                                      :key="j"
                                      @click="onClickCell(getVisibleDay(i,j))">
                                    {{getVisibleDay(i,j).getDate()}}
                                </span>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                    <div class="f-date-picker-actions">
                        <button @click="onClickToday">今天</button>
                        <button @click="onClickClear">清除</button>
                    </div>
                </div>
            </template>
        </f-popover>
    </div>
</template>

<script>
  import FInput from '../components/input';
  import FIcon from '../components/icon';
  import FPopover from '../components/popover';
  import ClickOutside from '../components/click-outside';
  import helper from './helper';

  export default {
    name: "date-picker"
    ,components:{FInput,FIcon,FPopover}
    ,directives:{ClickOutside}
    ,props:{
      firstDayOfWeek:{
        type:Number
      }
      ,value:{
        type:Date
        // ,default:()=>new Date()
      }
      ,scope:{
        type:Array
        //如果只有一个参数 直接 new Date(数字) 这个数字是毫秒数 而不是年份
        , default: () => [new Date(1900,0,1), helper.addYear(new Date(), 100)]
      }
    }
    ,data(){
      let [year, month] = helper.getYearMonthDate(this.value||new Date());
      return {
        // popVisible:false,
        mode:'days'
        // ,value:new Date()
        ,helper
        ,weekdays:['日','一','二','三','四','五','六']
        ,display:{year,month}
      }
    }
    ,mounted() {

    }
    ,computed:{
      visibleDays(){
        // console.log(this.value);
        let date = new Date(this.display.year, this.display.month, 1);
        let first = helper.firstDayOfMonth(date);
        let last = helper.lastDayOfMonth(date);
        let array = [];
        //生成1-本月最后一天
        /*let [year, month, day] = helper.getYearMonthDate(this.value);
        for(let i=first.getDate();i<=last.getDate();++i){
          array.push(new Date(year, month, i));
        }*/
        //getDate是日 getDay是周几
        /*let n = first.getDay() === 0 ? 6 : first.getDay() - 1;
        let array2 = [];
        for(let i=0;i<n;++i){
          array2.push(new Date(year, month, -i)); // 0是上一个月最后一天 -1是上月最后一天的前一天
        }
        array2 = array2.reverse();
        let m = 42 - array.length - array2.length;
        let array3 = [];
        for(let i=1;i<=m;++i){
          array3.push(new Date(year, month + 1, i));
        }
        return [...array2, ...array, ...array3];*/

        //算法二
        let offsetToTableFirstItem = first.getDay() === 0 ? 6 : first.getDay() - 1;
        let x = first - offsetToTableFirstItem * 3600 * 24 * 1000;
        for(let i=0;i<42;++i){
          array.push(new Date(x + i * 3600 * 24 * 1000));
        }
        // console.log(array)
        return array;
      }
      ,formattedvalue(){
        if(!this.value) return '';
        const [year,month,day] = helper.getYearMonthDate(this.value);
        return `${year}-${helper.pad2(month + 1)}-${helper.pad2(day)}`;
      }
      ,years(){
        return helper.range(this.scope[0].getFullYear(),this.scope[1].getFullYear()+1)
      }
    }
    ,methods:{
      onFocusInput(){
        // console.log(1)
        this.popVisible = true;
      }
      ,onBlurInput(){
        // console.log(2)
        this.popVisible = false;
      }
      ,onChange(){
        this.$refs.input.value = this.formattedvalue;
      }
      ,onInput(e){
        let value = e.target.value;
        var reg = /^\d{4}-\d{2}-\d{2}$/g;
        if(value.match(reg)){
          let [year, month, day] = value.split('-');
          month = month - 1;
          this.display = {year, month};
          this.$emit('input',new Date(year,month,day))
        }
      }
      ,onClickToday(){
        const now = new Date();
        const [year, month, day] = helper.getYearMonthDate(now);
        this.display = {year, month};
        this.$emit('input', new Date(year, month, day));
      }
      ,onClickClear(){
        this.$emit('input', undefined);
        this.$refs.popover.close();
      }
      ,onClickMonth(){
        if(this.mode !== 'month'){
          this.mode = 'month';
        }else{
          this.mode = 'day';
        }
      }
      ,onClickCell(date){
        if(!this.isCurrentMonth(date)) return;
        this.$emit('input', date);
        this.$refs.popover.close();
      }
      ,c(...classNames){
        return classNames.map(className => `f-date-picker-${className}`);
      }
      ,getVisibleDay(row,col){
        return this.visibleDays[(row-1)*7+col-1];
      }
      ,isCurrentMonth(date){
        let [year1, month1] = helper.getYearMonthDate(date);
        return year1 == this.display.year && month1 == this.display.month;
      }
      ,isSelected(date){
        if(!this.value) return false;
        let [y, m, d] = helper.getYearMonthDate(date);
        let [y2, m2, d2] = helper.getYearMonthDate(this.value);
        return y === y2 && m === m2 && d === d2;
      }
      ,isToday(date){
        let [y, m, d] = helper.getYearMonthDate(date);
        let [y2, m2, d2] = helper.getYearMonthDate(new Date());
        return y === y2 && m === m2 && d === d2;
      }
      ,onClickPrevYear(){
        const oldDate = new Date(this.display.year, this.display.month);
        const newDate = helper.addYear(oldDate, -1);
        const [year, month] = helper.getYearMonthDate(newDate);
        this.display = {year, month}
      }
      ,onClickPrevMonth(){
        const oldDate = new Date(this.display.year, this.display.month);
        const newDate = helper.addMonth(oldDate, -1);
        const [year, month] = helper.getYearMonthDate(newDate);
        this.display = {year, month}
      }
      ,onClickNextMonth(){
        const oldDate = new Date(this.display.year, this.display.month);
        const newDate = helper.addMonth(oldDate, 1);
        const [year, month] = helper.getYearMonthDate(newDate);
        this.display = {year, month}
      }
      ,onClickNextYear(){
        const oldDate = new Date(this.display.year, this.display.month);
        const newDate = helper.addYear(oldDate, 1);
        const [year, month] = helper.getYearMonthDate(newDate);
        this.display = {year, month}
      }
      ,onSelectYear(e){
        const year = e.target.value - 0;
        const d = new Date(year, this.display.month);
        if(d>=this.scope[0]&&d<=this.scope[1]){
          this.display.year = year;
        }else{
          alert('no');
          e.target.value = this.display.year;
        }
      }
      ,onSelectMonth(e){
        const month = e.target.value - 0;
        const d = new Date(this.display.year, month);
        if(d>=this.scope[0]&&d<=this.scope[1]){
          this.display.month = month;
        }else{
          alert('no');
          e.target.value = this.display.month;
        }
      }
    }
  }
</script>

<style lang="scss">
    @import '../components/var';
    .f-date-picker{
        &-nav{
            //background:red;
            display:flex;
        }
        &-popWrapper{
            padding:0;
        }
        &-navItem,&-cell,&-weekday{
            width:32px;
            height:32px;
            //border:1px solid $grey;
            display:inline-flex;
            justify-content: center;
            align-items: center;
        }
        &-cell{
            color:$grey;
            cursor:not-allowed;
            border-radius:$border-radius;
            &.currentMonth{
                color:black;
                &:hover{
                    background:$blue;
                    cursor:pointer;
                    color:white;
                }
            }
            &.today{
                background: $grey;
            }
            &.selected {
                border: 1px solid $blue;
            }
        }
        &-yearAndMonth{
            margin:auto;
        }
        &-selectMonth{
            width:224px;
            height:224px;
            display:flex;
            align-items: center;
            justify-content: center;
        }
        &-actions{
            padding:8px;
            text-align: right;
        }
    }
</style>
